package com.fd.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/jstl")
public class JSTLServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handleRequest(req, resp);

    }

    private void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//       在另外一个请求中获取session
        HttpSession session = req.getSession();

//        从session得到当前用户的登录信息
        Object loginUser = session.getAttribute("loginUser");

//        如果从session得到loginuser,就表示当前用户已经登录了,那么就继续执行下面的代码
        if (loginUser != null) {
            List<User> userList = new ArrayList<>();
            userList.add(new User(1, "zhang1"));
            userList.add(new User(2, "zhang2"));
            userList.add(new User(3, "zhang3"));
            userList.add(new User(4, "zhang4"));

//        用来创建一个Cookie
            Cookie cookie = new Cookie("fdNu   mber", "110110");

//       把cookie发送到客户端
            resp.addCookie(cookie);

            req.setAttribute("userList", userList);
            req.getRequestDispatcher("jstl.jsp").forward(req, resp);
            //如果从session没有获取到loginuser的值,说明没有登录,那么重定向到登录页面
        } else {
            resp.sendRedirect("login.jsp");
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handleRequest(req, resp);
    }
}
